# -*-coding:utf-8-*-

# import tornado.web
# import tornado.wsgi
import logging
import tornado
import pyrestful.rest
from tornado.options import define, options
import pyrestful.rest
from pyrestful import mediatypes
from pyrestful.rest import get, post, put, delete
import json
import os

define('port', default=18606, help='Run service on a specific port', type=int)
define('debug', help='Use debug settings for test purpose', type=bool)
options.parse_command_line()

'''
TAG hook

{
    "repository": {
        "url": "http://git.oschina.net/microembed/bora",
        "homepage": "http://git.oschina.net/microembed/bora",
        "name": "bora",
        "description": "distributed cluster"
    },
    "hook_name": "tag_push_hooks",
    "after": "d9a030d83932b466e7cc84c1b6e8c5241dfhdfhdfh",
    "project": {
        "git_http_url": "https://git.oschina.net/microembed/bora.git",
        "git_ssh_url": "git@git.oschina.net:microembed/bora.git",
        "default_branch": "master",
        "name": "bora",
        "git_svn_url": "svn://git.oschina.net/microembed/bora",
        "url": "http://git.oschina.net/microembed/bora",
        "path": "bora",
        "path_with_namespace": "microembed/bora",
        "namespace": "microembed"
    },
    "password": "120000",
    "ref": "refs/tags/tagname",
    "before": "00000000"
}
'''

'''
PUSH hook

{
    "repository": {
        "url": "https://git.oschina.net/microembed/bora_bin",
        "homepage": "https://git.oschina.net/microembed/bora_bin",
        "name": "bora_bin",
        "description": "byte compiled code of bora project"
    },
    "hook_name": "push_hooks",
    "commits": [
        {
            "url": "https://git.oschina.net/microembed/bora_bin/commit/910837247f6bf73ca26797d14f164dcba98d9d62",
            "timestamp": "2017-09-20T21:39:34+08:00",
            "message": "update",
            "id": "910837247f6bf73ca26797d14f164dcba98d9d62",
            "author": {
                "email": "zhoujiexiong@foxmail.com",
                "name": "zhoujiexiong",
                "time": "2017-09-20T21:39:34+08:00"
            }
        }
    ],
    "after": "910837247f6bf73ca26797d14f164dcba98d9d62",
    "user": {
        "username": "microembed",
        "url": "https://git.oschina.net/microembed",
        "name": "microembed"
    },
    "password": "120000",
    "before": "a9980cf9063d644136897d454b44b89f89702e5d",
    "commits_more_than_ten": false,
    "user_id": 367275,
    "ref": "refs/heads/master",
    "project": {
        "git_http_url": "https://git.oschina.net/microembed/bora_bin.git",
        "git_ssh_url": "git@git.oschina.net:microembed/bora_bin.git",
        "path_with_namespace": "microembed/bora_bin",
        "name": "bora_bin",
        "git_svn_url": "svn://git.oschina.net/microembed/bora_bin",
        "url": "https://git.oschina.net/microembed/bora_bin",
        "namespace": "microembed",
        "path": "bora_bin",
        "name_with_namespace": "microembed/bora_bin",
        "default_branch": "master"
    },
    "total_commits_count": 1,
    "user_name": "microembed"
}
'''

DEPLOY_PASS = '120000'


class DeployHandler(pyrestful.rest.RestHandler):
    # POST → http://119.23.25.240:18601/deploy/bora
    @post(_path='/deploy/bora', _produces=mediatypes.APPLICATION_JSON)
    def deploy_bora(self):
        request = json.loads(self.request.body)
        if request['password'] != DEPLOY_PASS:
            self.set_status(401)
            return
        git_ssh_url = request['project']['git_ssh_url']
        tagname = request['ref'].split('/')[2]
        cmd = './scripts/deploy_bora.sh %s %s' % (git_ssh_url, tagname)
        os.system(cmd)

    # POST -> http://deploy.microembed.net/bora_bin
    @post(_path='/deploy/bora_bin', _produces=mediatypes.APPLICATION_JSON)
    def deploy_bora_bin(self):
        request = json.loads(self.request.body)
        print request
        if request['password'] != DEPLOY_PASS:
            self.set_status(401)
            return
        git_ssh_url = request['project']['git_ssh_url']
        # tagname = request['ref'].split('/')[2]
        commit = request['after']
        project_name = request['project']['name']
        cmd = './scripts/deploy_bora_bin.sh %s %s %s' % (git_ssh_url, commit, project_name)
        os.system(cmd)


handlers = [
    DeployHandler,
]


def main():
    logger = logging.getLogger()
    # application = tornado.web.Application(routes)
    application = pyrestful.rest.RestService(handlers)
    application.listen(options.port, address='127.0.0.1')
    logger.info('api server start at %d' % options.port)
    tornado.ioloop.IOLoop.instance().start()


if __name__ == '__main__':
    main()
